﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BCCommon;
using BCEntity.MakeStaticPagingComponent.TemplateTag;
using Dapper;

namespace BCData.MakeStaticPagingComponent.TemplateTag
{
    /// <summary>
    /// 模板标签数据处理
    /// </summary>
    public class TemplateTagData : ITemplateTagData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY = @"SELECT TemplateTagId,TagName,TagDescription,TagValue,CreateTime,UpdateTime
                                        FROM TemplateTag";
        public TemplateTagData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public TemplateTagEntity Add(TemplateTagEntity templateTagEntity)
        {
            string sql = @"INSERT INTO TemplateTag(TagName,TagDescription,TagValue)
                                VALUES(?TagName,?TagDescription,?TagValue);";
            sql = string.Format("{0} {1} WHERE TemplateTagId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TagName", templateTagEntity.TagName, DbType.AnsiString, size: 100);
            parameters.Add("?TagDescription", templateTagEntity.TagDescription, DbType.AnsiString, size: 400);
            parameters.Add("?TagValue", templateTagEntity.TagValue, DbType.String);
            return this.databaseContext.Master.QueryEntity<TemplateTagEntity>(sql, parameters, databaseContext.Transaction);
        }

        public bool CheckTemplateTagExists(string tagName)
        {
            string sql = @" SELECT 1 FROM TemplateTag WHERE TagName=?TagName LIMIT 1";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TagName", tagName, DbType.AnsiString, size: 100);
            object result = this.databaseContext.Slave.ExecuteScalar(sql, parameters);
            return result != null;
        }

        public bool CheckTemplateTagExists(long templateTagId)
        {
            string sql = @" SELECT 1 FROM TemplateTag WHERE TemplateTagId=?TemplateTagId LIMIT 1";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TemplateTagId", templateTagId, DbType.Int64, size: 20);
            object result = this.databaseContext.Slave.ExecuteScalar(sql, parameters);
            return result != null;
        }

        public void Delete(long templateTagId)
        {
            string sql = @"DELETE FROM TemplateTag WHERE TemplateTagId=?TemplateTagId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TemplateTagId", templateTagId, DbType.Int64, size: 20);
            this.databaseContext.Master.Execute(sql, parameters, databaseContext.Transaction);
        }

        public TemplateTagEntity GetTemplateTagEntity(string tagName)
        {
            string sql = " WHERE TagName=?TagName";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TagName", tagName, DbType.AnsiString, size: 100);
            return this.databaseContext.Slave.QueryEntity<TemplateTagEntity>(string.Concat(QUERY, sql), parameters);
        }
        
        public TemplateTagEntity GetTemplateTagEntity(long templateTagId)
        {
            string sql = " WHERE A.TemplateTagId=?TemplateTagId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TemplateTagId", templateTagId, DbType.Int64);
            return this.databaseContext.Slave.QueryEntity<TemplateTagEntity>(string.Concat(QUERY, sql), parameters);
        }

        public IEnumerable<string> GetTemplateTagName()
        {
            string sql = "SELECT TagName FROM TemplateTag";
            return this.databaseContext.Slave.Query<string>(sql);
        }

        public TemplateTagEntity Update(TemplateTagEntity templateTagEntity)
        {
            string sql = @"UPDATE TemplateTag SET
                                TagName=?TagName,
                                TagDescription=?TagDescription,
                                TagValue=?TagValue
                            WHERE TemplateTagId=?TemplateTagId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TemplateTagId", templateTagEntity.TemplateTagId, DbType.Int64, size: 20);
            parameters.Add("?TagName", templateTagEntity.TagName, DbType.AnsiString, size: 100);
            parameters.Add("?TagDescription", templateTagEntity.TagDescription, DbType.AnsiString, size: 400);
            parameters.Add("?TagValue", templateTagEntity.TagValue, DbType.String);
            return this.databaseContext.Master.QueryEntity<TemplateTagEntity>(string.Concat(sql, string.Concat(QUERY, " WHERE TemplateTagId=?TemplateTagId;")), parameters, databaseContext.Transaction);
        }
        
        public IEnumerable<TemplateTagEntity> Get()
        {
            return this.databaseContext.Slave.Query<TemplateTagEntity>(QUERY);
        }
        
        public IEnumerable<TemplateTagEntity> Query(string tagName, string tagDescription, DateTime? start, DateTime? end, string sortField, bool? ascending, out int dataCount, int index, int size)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(tagName))
            {
                wheres.Add("TagName=?TagName");
                parameters.Add("?TagName", tagName, DbType.AnsiString, size: 100);
            }
            if (!string.IsNullOrWhiteSpace(tagDescription))
            {
                wheres.Add("TagDescription LIKE CONCAT('%',?TagDescription,'%')");
                parameters.Add("?TagDescription", tagDescription, DbType.AnsiString,size:30);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {5} {4} LIMIT {2},{3}; 
                               SELECT Count(1) FROM TemplateTag {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (index == 0 ? 0 : index - 1) * size,
                  size,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC",
                  string.IsNullOrWhiteSpace(sortField) ? "CreateTime" : sortField);

            var result = this.databaseContext.Slave.QueryMultiple<TemplateTagEntity, int>(sql, parameters);

            dataCount = result.Item2;

            return result.Item1;
        }
    }
}
